package com.epalmpay.service.weixin.impl;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

import com.epalmpay.service.weixin.ITokenService;
import com.epalmpay.util.Token;
import com.epalmpay.util.Tools;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;



@Service("tokenService")
public class TokenServiceImpl implements ITokenService{
	      LoadingCache<String, Token> gettoken = CacheBuilder.newBuilder().maximumSize(10000)
	              .expireAfterWrite(3L, TimeUnit.DAYS).build(new CacheLoader<String, Token>() {
	                  @Override
	                  public Token load(String memberId) throws Exception {
	                	  System.out.println("-------------------------------------------会员缓存加载中-----------------------------"+memberId);
	                      Token token=new Token();    
	                      token.setKey(memberId);   
	                      token.setValue(Tools.getRandomNumABC(6));
	                      return token;
	                  }
	            });
	        public   Boolean checkToken(String memberId,String token) {
	            try {
	            	if(Tools.isEmpty(memberId)||Tools.isEmpty(token)){
	            		 return false;
	            	}
	            	Token access_token = gettoken.get(memberId);
	            	if(access_token.getValue().equals(token)){
	            		 return true;
	            	  }
	                return false;
	            } catch (ExecutionException e) {
	                e.printStackTrace();
	            }
	            return false;
	        }
	        
	        
			@Override
			public void refresh(String memberId) {
				gettoken.refresh(memberId);
			}
	      
			@Override
			public void invalidate(String memberId) {
				gettoken.invalidate(memberId);
			}

			@Override
			public Token getTokenInfo(String memberId) {
				try {
					Token access_token = gettoken.get(memberId);
					return access_token;
				} catch (ExecutionException e) {
					e.printStackTrace();
				}
				return null;
			}
   
}
